# app/api/wechat.py

from flask import Blueprint, request, current_app
import hashlib, time, xmltodict
from app.services.salary_service import SalaryService

wechat_bp = Blueprint('wechat', __name__)

def create_reply(to_user, from_user, content):
    reply = {'xml': {
        'ToUserName': from_user,
        'FromUserName': to_user,
        'CreateTime': int(time.time()),
        'MsgType': 'text',
        'Content': content
    }}
    return xmltodict.unparse(reply)

def format_salary_info(s):
    txt = (
        f"ID：{s['id']}\n"
        f"公司：{s['company']}\n"
        f"职位：{s['position']}\n"
        f"城市：{s['city']}\n"
        f"月薪：{s['base_salary']}k\n"
        f"月数：{s['months']}月\n"
        f"年终奖：{s['bonus']}k\n"
    )
    if s.get('signing_bonus'):
        txt += f"签字费：{s['signing_bonus']}k\n"
    if s.get('stock'):
        txt += f"股票期权：{s['stock']}\n"
    if s.get('remark'):
        txt += f"备注：{s['remark']}\n"
    return txt

def handle_text_message(content, from_user, to_user):
    host = request.url_root
    current_app.logger.info(f"微信消息内容：{content}")
    try:
        # 菜单
        if content == '菜单':
            menu = (
                "【查询功能】\n"
                "1. 简单查询：查询 <关键词> 例：查询 华为\n"
                "2. 条件查询：支持以下字段：\n"
                "   company=公司名(模糊)\n"
                "   position=职位(模糊)\n"
                "   city=城市(模糊)\n"
                "   min_salary=最低月薪\n"
                "   max_salary=最高月薪\n"
                "   education=学历(大专/本科/硕士/博士)\n"
                "   type=类型(校招/社招/实习)\n"
                "   status=状态(pending/approved/rejected)\n"
                "   示例：查询 company=华为 max_salary=40 education=本科\n"
                "3. 分页查询：在查询后加 page=<页码>\n"
                "   示例：查询 华为 page=2\n"
                "4. ID 查询：详情 <ID> 例：详情 3\n\n"
                "【分享功能】\n"
                "1. 单条上传：发送“分享”获取模板\n"
                f"2. 批量上传：浏览器打开 {host}salary/upload\n\n"
                "【更新操作】\n"
                "删除：删除 <ID> 例：删除 5\n"
                "更新：更新 <ID> key=值 ... 例：更新 5 city=深圳\n\n"
                "【管理员功能】(输入：管理员 <密码>，验证正确可使用操作)\n"

            )
            return create_reply(to_user, from_user, menu)

        # 查询
        if content.startswith('查询'):
            parts = content.replace('查询','').strip().split()
            filters, page = {}, 1
            filtered_parts=[]
            for p in parts:
                if '=' in p:
                    k,v = p.split('=',1)
                    if k=='page': page=int(v)
                    else:
                        filters[k]=v
                        filtered_parts.append(p)
                else:
                    filters['keyword']=p
                    filtered_parts.append(p)  # 保留 keyword
            res = SalaryService.search_salaries(filters, page)
            if res['items']:
                txt = f"查询结果 ({res['current_page']}/{res['pages']}页)：\n"
                for it in res['items']:
                    txt += format_salary_info(it) + "————\n"
                #print(filtered_parts)
                if res['has_next']:
                    # 初始化提示信息列表
                    prompts = []

                    # 如果不是第一页，添加上一页提示
                    if page > 1:

                        prompts.append(f" 发送“查询 {' '.join(filtered_parts)} page={page-1}”查看上一页\n")

                    # 如果不是最后一页，添加下一页提示
                    if res['has_next']:  # 假设res['has_next']表示还有下一页
                        prompts.append(f"发送“查询 {' '.join(filtered_parts)} page={page+1}”查看下一页")

                    # 如果有提示信息，则添加到txt中
                    if prompts:
                        txt += " ".join(prompts)
            else:
                txt = "未找到匹配薪资"
            return create_reply(to_user, from_user, txt)

        # 详情
        if content.startswith('详情'):
            sid = int(content.replace('详情','').strip())
            sal = SalaryService.get_salary_detail(sid)
            return create_reply(to_user, from_user, "薪资详情：\n" + format_salary_info(sal.to_dict()))

        # 删除
        if content.startswith('删除'):
            sid = int(content.replace('删除','').strip())
            SalaryService.delete_salary(sid)
            return create_reply(to_user, from_user, f"已删除 ID={sid}")

        # 更新
        if content.startswith('更新'):
            parts = content.replace('更新','').strip().split()
            sid = int(parts[0]); data = {}
            for p in parts[1:]:
                if '=' in p:
                    k,v = p.split('=',1)
                    data[k] = v
            sal = SalaryService.update_salary(sid, data)
            return create_reply(to_user, from_user, "更新成功：\n" + format_salary_info(sal.to_dict()))

        # 分享模板
        if content == '分享':
            tpl = (
                "请按格式分享薪资：\n"
                "签字费/股票期权可忽略不填\n"
                "公司|职位|城市|月薪(k)|月数|年终奖(k)|签字费(k)|股票期权\n"
                "示例：字节跳动|后端算法实习|北京|35|12|100|20|4年40万"
            )
            return create_reply(to_user, from_user, tpl)

        # 单条分享
        if '|' in content:
            sal = SalaryService.create_salary_from_wechat(content, from_user)
            return create_reply(to_user, from_user, "分享已提交，待审核")

        # 管理员验证
        if content.startswith('管理员'):
            parts = content.split()
            if len(parts)!=2:
                raise ValueError("格式：管理员 <密码>")
            if not SalaryService.verify_admin(parts[1]):
                raise ValueError("管理员密码错误")
            return create_reply(to_user, from_user,
                                "管理员验证成功！可用：\n"
                                "1.待审核\n2.通过 <ID> <密码>\n3.拒绝 <ID> <密码> <原因>"
                                )

        # 待审核
        if content == '待审核':
            res = SalaryService.get_pending_salaries_all()
            if res:
                txt = f"待审核({len(res)}条)：\n"
                for it in res:
                    txt += format_salary_info(it) + "————\n"
            else:
                txt = "暂无待审核记录"
            return create_reply(to_user, from_user, txt)

        # 通过
        if content.startswith('通过'):
            parts = content.split()
            if len(parts)!=3:
                raise ValueError("格式：通过 <ID> <密码>")
            SalaryService.approve_salary(int(parts[1]), parts[2])
            return create_reply(to_user, from_user, f"已通过 ID={parts[1]}")

        # 拒绝
        if content.startswith('拒绝'):
            parts = content.split()
            if len(parts)<4:
                raise ValueError("格式：拒绝 <ID> <密码> <原因>")
            sid,pw,reason = int(parts[1]),parts[2],' '.join(parts[3:])
            SalaryService.reject_salary(sid, pw, reason)
            return create_reply(to_user, from_user, f"已拒绝 ID={sid}")

        # 未识别
        return create_reply(to_user, from_user, f"无法识别命令：{content}\n发送“菜单”获取帮助")

    except Exception as e:
        current_app.logger.error(f"处理微信命令出错：{e}")
        return create_reply(to_user, from_user, f"执行失败：{e}\n发送“菜单”查看示例")

@wechat_bp.route('/wechat', methods=['GET','POST'])
def wechat():
    if request.method == 'GET':
        sig = request.args.get('signature',''); ts=request.args.get('timestamp','')
        nonce=request.args.get('nonce',''); echo=request.args.get('echostr','')
        token = current_app.config['WECHAT_TOKEN']
        tmp = ''.join(sorted([token,ts,nonce]))
        if hashlib.sha1(tmp.encode()).hexdigest()==sig:
            return echo
        return '签名校验失败'
    xml = request.data or b''
    current_app.logger.info(f"微信POST args={request.args} data={xml}")
    msg = xmltodict.parse(xml)
    ct = msg['xml']['Content'].strip()
    fu = msg['xml']['FromUserName']; tu = msg['xml']['ToUserName']
    return handle_text_message(ct, fu, tu)